﻿using System;
using System.IO;

namespace ExcelAutomator.Tests
{
	public static class TestHelper
	{
		public static string GetStringResource(string resourceName, Type assemblyType)
		{
			using (var resourceStream = assemblyType.Assembly.GetManifestResourceStream(resourceName))
			{
				if (resourceStream == null)
				{
					throw new InvalidOperationException("Failed to load resource named '" + resourceName + "'.");
				}
				if (resourceStream.Length == 0)
				{
					throw new InvalidOperationException("Resource named '" + resourceName + "' has a length of 0.");
				}
				var sr = new StreamReader(resourceStream);
				return sr.ReadToEnd();
			}
		}

		public static string GetStringResource(string resourceName)
		{
			return GetStringResource(resourceName, typeof(TestHelper));
		}

		#region ExtractResourceFromAssembly

		public static void ExtractResourceFromAssembly(byte[] resource, string resourceName, string folder)
		{
			folder = Path.Combine(Environment.CurrentDirectory, folder);

			if (!Directory.Exists(folder))
			{
				Directory.CreateDirectory(folder);
			}

			using (var fs = new FileStream(Path.Combine(folder, resourceName),
																		 FileMode.Create,
																		 FileAccess.Write,
																		 FileShare.Delete))
			{
				fs.Write(resource, 0, resource.Length);
			}
		}

		public static void ExtractResourceFromAssembly(byte[] resource, string resourceName)
		{
			ExtractResourceFromAssembly(resource, resourceName, string.Empty);
		}

		#endregion
	}
}
